﻿using JewererBasic.BO;
using JewererBasic.Classes;
using JewererBasic.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace JewererBasic.Controllers
{
    public class ToolController : Controller
    {
        private MSQDBEntities db = new MSQDBEntities();

        private List<TYPE> listTypes;
        private List<UNIT> listUnits;

        #region Index Home
        public ActionResult Index()
        {
            ImportedTools.Clear();
            ExportedTools.Clear();

            return View(db.TOOLs.ToList());
        }

        [HttpPost]
        public ActionResult Index(FormCollection fc)
        {
            ImportedTools.Clear();
            ExportedTools.Clear();
            
            if (fc["submit"] == "SEARCH")
            {
                string searchId = fc["txtSearchId"];
                return View(ToolBO.Search(searchId));
            }
            else if (fc["submit"] == "IMPORT")
            {
                return RedirectToAction("Import");
            }
            else if (fc["submit"] == "EXPORT")
            {
                return RedirectToAction("TestingExport");
            }
            else if (fc["submit"] == "HISTORY")
            {
                ClearSearchHistory();
                return RedirectToAction("History");
            }

            return View(db.TOOLs.ToList());
        }

        public ActionResult AddTool(string id, int quantity)
        {
            bool result = true;

            TOOL s = new TOOL();
            s.Id = id;
            s.Quantity = quantity;

            result = ToolBO.Add(s);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region Import
        private static List<ServiceTool> ImportedTools = new List<ServiceTool>();
        public ActionResult Import()
        {
            ViewBag.CurrentUser = CurrentUser.UserID;
            ViewBag.CurrentDate = DateTime.Now.Date.ToShortDateString();

            return View(ImportedTools);
        }

        public JsonResult SaveImport()
        {
            TOOL_IMPORT si = new TOOL_IMPORT();
            List<TOOL_IMPORT_DETAIL> listSid = new List<TOOL_IMPORT_DETAIL>();
            foreach (var item in ImportedTools)
            {
                TOOL_IMPORT_DETAIL sid = new TOOL_IMPORT_DETAIL();
                sid.IdTool = item.Id;
                sid.Quantity = item.Quantity;
                sid.Price = item.Price;
                sid.TotalCost = item.TotalCost;
                sid.Reason = item.Reason;
                listSid.Add(sid);
            }

            ToolBO.Import(si, listSid);
            ImportedTools.Clear();

            return Json(new { id = si.Id }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region Testing Export
        private static List<ServiceTool> ExportedTools = new List<ServiceTool>();
        public ActionResult Export()
        {
            ViewBag.CurrentUser = CurrentUser.UserID;
            ViewBag.CurrentDate = DateTime.Now.Date.ToShortDateString();

            return View(ExportedTools);
        }

        public JsonResult SaveTestingExport()
        {
            TOOL_EXPORT se = new TOOL_EXPORT();
            List<TOOL_EXPORT_DETAIL> listSesd = new List<TOOL_EXPORT_DETAIL>();
            foreach (var item in ExportedTools)
            {
                TOOL_EXPORT_DETAIL sesd = new TOOL_EXPORT_DETAIL();
                sesd.IdTool = item.Id;
                sesd.Quantity = item.Quantity;
                sesd.Price = item.Price;
                sesd.TotalCost = item.TotalCost;
                sesd.Reason = item.Reason;
                listSesd.Add(sesd);
            }

            ToolBO.Export(se, listSesd);

            ExportedTools.Clear();

            return Json(new { result = true, id = se.Id }, JsonRequestBehavior.AllowGet);
        }
        #endregion
        
        #region History
        private static string id;
        private static DateTime? makedDateFrom;
        private static DateTime? makedDateTo;
        private static bool importBool = true;
        private static bool exportBool = true;
        public ActionResult History()
        {
            ViewBag.Id = id;
            ViewBag.MakedDateFrom = makedDateFrom == null ? null : makedDateFrom.Value.ToString("yyyy-MM-dd");
            ViewBag.MakedDateTo = makedDateTo == null ? null : makedDateTo.Value.ToString("yyyy-MM-dd");
            ViewBag.ImportBool = importBool;
            ViewBag.ExportBool = exportBool;

            return View(ToolBO.History(id, makedDateFrom, makedDateTo, Convert.ToBoolean(importBool), Convert.ToBoolean(exportBool)));
        }

        [HttpPost]
        public ActionResult History(FormCollection fc)
        {
            if (fc["submit"] == "HISTORY")
            {
                id = fc["txtIdTool"];
                string dateFrom = fc["makedDateFrom"];
                string dateTo = fc["makedDateTo"];
                string import = fc["ckboxImport"];
                string export = fc["ckboxExport"];

                makedDateFrom = null;
                if (String.IsNullOrEmpty(dateFrom) == false)
                {
                    makedDateFrom = Convert.ToDateTime(dateFrom);
                }
                makedDateTo = null;
                if (String.IsNullOrEmpty(dateTo) == false)
                {
                    makedDateTo = Convert.ToDateTime(dateTo);
                }

                bool tmp;
                importBool = false;
                exportBool = false;

                if (Boolean.TryParse(import, out tmp) == false)
                {
                    importBool = true;
                }
                if (Boolean.TryParse(export, out tmp) == false)
                {
                    exportBool = true;
                }
            }
            else if (fc["submit"] == "CLEAR")
            {
                ClearSearchHistory();
            }

            ViewBag.Id = id;
            ViewBag.MakedDateFrom = makedDateFrom == null ? null : makedDateFrom.Value.ToString("yyyy-MM-dd");
            ViewBag.MakedDateTo = makedDateTo == null ? null : makedDateTo.Value.ToString("yyyy-MM-dd");
            ViewBag.ImportBool = importBool;
            ViewBag.ExportBool = exportBool;

            return View(ToolBO.History(id, makedDateFrom, makedDateTo, Convert.ToBoolean(importBool), Convert.ToBoolean(exportBool)));
        }

        private void ClearSearchHistory()
        {
            id = "";
            makedDateFrom = null;
            makedDateTo = null;
            importBool = true;
            exportBool = true;
        }
        #endregion

        #region Json
        public ActionResult SaveToDb(List<ToolViewModel> Tools)
        {
            bool result = true;

            foreach (var item in Tools)
            {
                TOOL tool = new TOOL();
                tool.Id = item.Id;
                tool.Quantity = item.Quantity;

                ToolBO.Add(tool);
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult ClearImportForm()
        {
            bool result = true;

            ImportedTools.Clear();

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult ClearTestingExportForm()
        {
            bool result = true;

            ExportedTools.Clear();

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult IsToolExisted(string id)
        {
            bool result;

            TOOL p = db.TOOLs.Find(id);
            if (p == null)
            {
                result = false;
            }
            else
            {
                result = true;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AddImport(string id, int quantity, int price, string reason)
        {
            bool result = true;

            ImportedTools.Add(new ServiceTool() { Id = id, Quantity = quantity, Reason = reason, Price = price, TotalCost = quantity * price });

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AddTestingExport(string id, int quantity, int price, string reason)
        {
            bool result = true;

            ExportedTools.Add(new ServiceTool() { Id = id, Quantity = quantity, Reason = reason, Price = price, TotalCost = quantity * price });

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetTools(string query = null)
        {
            var result = from d in db.TOOLs
                         where d.Id.Contains(query)
                         select d.Id;
            var s = result.ToList();
            return Json(result.ToList(), JsonRequestBehavior.AllowGet);
        }

        public JsonResult UpdateImportTool(string id, int quantity, int price, string reason)
        {
            bool result = true;

            ServiceTool s = ImportedTools.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
            {
                s.Quantity = quantity;
                s.Price = price;
                s.TotalCost = s.Quantity * s.Price;
                s.Reason = reason;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteImportTool(string id)
        {
            bool result = true;

            ServiceTool s = ImportedTools.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
                ImportedTools.Remove(s);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult UpdateTestingExportTool(string id, int quantity, int price, string reason)
        {
            bool result = true;

            ServiceTool s = ExportedTools.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
            {
                s.Quantity = quantity;
                s.Price = price;
                s.TotalCost = s.Quantity * s.Price;
                s.Reason = reason;
            }

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteTestingExportTool(string id)
        {
            bool result = true;

            ServiceTool s = ExportedTools.Where(m => m.Id == id).FirstOrDefault();
            if (s == null)
                result = false;
            else
                ExportedTools.Remove(s);

            return Json(new { result }, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}
